//
//  LanguageViewController.swift
//  GitOSC-Swift
//
//  Created by 李萍 on 15/12/30.
//  Copyright © 2015年 李萍. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class LanguageViewController: UITableViewController {
    
    private var languages = [GTLanguage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.fetchForLanguage()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //tableview 列表
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
        cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
        
        if indexPath.row < languages.count {
            cell.textLabel?.text = "\(languages[indexPath.row].name)"
        }
        
        return cell
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return languages.count
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        self.tableView!.deselectRowAtIndexPath(indexPath, animated: true)
        
        let projectTableVC = ProjectsTableViewController(projectType: 7)
        projectTableVC.title = languages[indexPath.row].name
        projectTableVC.languageID = languages[indexPath.row].languageID
        projectTableVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(projectTableVC, animated: true)
    }
    
    //请求数据language
    func fetchForLanguage() -> Void {
        Alamofire.Manager.sharedInstance.request(Method.GET, GITAPI_HTTPS_PREFIX+GITAPI_PROJECTS+GITAPI_LANGUAGE).responseJSON{ response in
            // result of response serialization
            if let results = response.result.value {
                
                var jsonArray = JSON(results).array!
                
                for var i in 0 ..< jsonArray.count {
                                
                    let language = GTLanguage(json:jsonArray[i])
                    
                    self.languages.append(language)
                }
                
                self.tableView.reloadData()
            }
        }
    }
}
